package com.sysmanage.permissions.controls;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sysmanage.common.tools.util.DictionaryMemoryUtils;
import com.sysmanage.common.tools.util.Encrypt;
import com.sysmanage.framework.controls.struts2.BaseTg;
import com.sysmanage.permissions.ConstCode;
import com.sysmanage.permissions.common.MenuJsonItem;
import com.sysmanage.permissions.model.Resources;
import com.sysmanage.permissions.model.Users;
import com.sysmanage.permissions.service.IUserService;

/** 
  * @ClassName: LoginTg 
  * @Description: 用户登录
  * @author XXXX@163.com
  * @date 2011-9-29 上午10:43:55 
  *  
  */
@Scope("prototype")
@Controller(value="loginTgControl")
public class LoginTg extends BaseTg{
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	private String rememberMe;
		public String getRememberMe() {
		return rememberMe;
	}
	public void setRememberMe(String rememberMe) {
		this.rememberMe = rememberMe;
	}
	
	/**
	 * @return the agentname
	 */
	public String getAgentname() {
		return agentname;
	}
	/**
	 * @param agentname the agentname to set
	 */
	public void setAgentname(String agentname) {
		this.agentname = agentname;
	}
	private String agentname;
	private String username;
	private String password;
	private String targetName;
	public String getTargetName() {
		return targetName;
	}
	public void setTargetName(String targetName) {
		this.targetName = targetName;
	}
	@Autowired
	private IUserService userService;
	
	/** 
	  * @Title: login 
	  * @Description: 用户登录方法
	  * @param @return
	  * @return String
	  * @throws 
	  */
	@SuppressWarnings("unchecked")
	public String login() {
		UsernamePasswordToken token=null;
		List<Users> userList = null;
		if(agentname == null||"".equals(agentname)){
			Encrypt enc = new Encrypt();
			token = new UsernamePasswordToken(username, enc.encString(password), Boolean.valueOf(rememberMe));
		}else{
			userList = userService.findList("from Users where logonid ='"+agentname+"'");
			
			for (int i = 0; i < userList.size(); i++) {
				System.out.println(userList.get(i).getLogonid());
				//TODO
				//token = new UsernamePasswordToken(userList.get(i).getLogonid(), userList.get(i).getPassword(), Boolean.valueOf(rememberMe));
				token = new UsernamePasswordToken(userList.get(i).getLogonid(), userList.get(i).getPassword(), Boolean.valueOf(rememberMe));
				break;
			}
		}
		Subject user = SecurityUtils.getSubject();
		try {
			user.login(token);
			
			//构造菜单的json对象			
			//设置用户对象
			List<Resources> list = (List<Resources>) SecurityUtils.getSubject().getSession().getAttribute("resourceList");
			//存放没有父级菜单权限的父级菜单
			List<Resources> tmpMenus = new ArrayList<Resources>();
			//所有子菜单的父级菜单加入列表
			List<Integer> menuIdList = new ArrayList<Integer>();
			
			for(int i=0;i<list.size();i++)
			{
				Resources temp = (Resources)list.get(i);
				menuIdList.add(temp.getId());				
			}
			boolean hasNode = false;
			for(int i=0;i<list.size();i++)
			{
				Resources temp = (Resources)list.get(i);
				Resources tempParent = temp.getParent();
				hasNode = false;
				while(!hasNode)
				{	
					hasNode = true;
					if(ConstCode.CRM_SYSTEM_ID==temp.getSystem().getId()&&(tempParent!=null&&ConstCode.CRM_SYSTEM_RES_ID!=tempParent.getId()))
					{
						if(!menuIdList.contains(tempParent.getId()))
						{
							menuIdList.add(temp.getParent().getId());
							tmpMenus.add(tempParent);
							temp = tempParent;
							tempParent.getParent();
							hasNode = false;
						}
					}
				}
				//if(menuIdList.contains(temp.getParent()))			
			}
			tmpMenus.addAll(list);
			
			
			//先获取一级菜单的列表
			List<Resources> firstMenu = new ArrayList<Resources>();
			for(int i=0;i<tmpMenus.size();i++){
				Resources temp = (Resources)tmpMenus.get(i);
				if(ConstCode.CRM_SYSTEM_ID==temp.getSystem().getId()&&(temp.getParent()!=null&&ConstCode.CRM_SYSTEM_RES_ID==temp.getParent().getId()))
				{					
					firstMenu.add(temp);
				}
			}
			StringBuffer firstMenuSb = new StringBuffer();
			JsonConfig config = new JsonConfig();  
			config.setJsonPropertyFilter(new PropertyFilter()  
			{  
			    @Override  
			    public boolean apply(Object source, String name, Object value)  
			    {  
			        return value == null;  
			    }  
			}); 
			//List<MenuJsonItem> firstMenuItem = new ArrayList<MenuJsonItem>();
			//构造子菜单的json对象
			//Map<String,MenuJsonItem> secMenuMap = new HashMap<String,MenuJsonItem>();
			StringBuffer secMenuSb = new StringBuffer("{");
			Collections.sort(firstMenu, new Comparator<Resources>(){
				
				public int compare(Resources o1, Resources o2) {
					return o1.getOrderid().compareTo(o2.getOrderid());
				}
				
			});			
			for(int j=0;j<firstMenu.size();j++)
			{	
				Resources item = firstMenu.get(j);

				if(j==0)
				{
					firstMenuSb.append("<li class=\"selected\"><a name=\"menu"+j+"\" href=\"javascript:;\" title=\""+item.getName()+"\"><span>"+item.getName()+"</span></a></li>");
					secMenuSb.append("menu"+j+":");
					secMenuSb.append( JSONArray.fromObject(treeGen(item,tmpMenus),config).toString());
					//secMenuSb.append("]");					
				}
				else
				{
					firstMenuSb.append("<li><a name=\"menu"+j+"\" href=\"javascript:;\" title=\""+item.getName()+"\"><span>"+item.getName()+"</span></a></li>");
					secMenuSb.append(",menu"+j+":");
					secMenuSb.append( JSONArray.fromObject(treeGen(item,tmpMenus),config).toString());
					//secMenuSb.append("]");
				}				
			}
			secMenuSb.append("};");	
			
			request.setAttribute("strFirstMenu", firstMenuSb.toString());
			request.setAttribute("strSecMenu", secMenuSb.toString());
			//拼登录的用户名和公司名
			String loginStr = this.getUser().getName()+"(" + 
					DictionaryMemoryUtils.getInstance().getNameByNickAndKey(ConstCode.DIC_NICK_NAME_COMPANY, this.getCurrentUserCompanyID()+"")
					+")";
			request.setAttribute("loginStr", loginStr);
			/*
			
			HasParent.isHasParent();
			List<Resources> list = (List<Resources>) SecurityUtils.getSubject().getSession().getAttribute("resourceList");
			
			HasParent.returnCurrentObj(null,request);
//			List<Resources> xxx = HasParent.returnCurrentObj(null,request);
//			System.out.println(request.getAttribute("jsonOne"));
//			System.out.println(request.getAttribute("jsonTwo"));
			
			
			List<CloneResources> resource = new ArrayList<CloneResources>();
			//先找出权限系统的系统资源项ID
			Integer rootId = 0;
			for(int i=0;i<list.size();i++){
				Resources temp = (Resources)list.get(i);
				if(ConstCode.CRM_SYSTEM_ID==temp.getSystem().getId()&&ConstCode.RESOURCE_TYPE_SYSTEM.equals(temp.getResourcetype()))
				{
					rootId = temp.getId();
				}
			}
			
			for(int i=0;i<list.size();i++){
				Resources temp = (Resources)list.get(i);
				if(ConstCode.CRM_SYSTEM_ID==temp.getSystem().getId()&&!(ConstCode.RESOURCE_TYPE_SYSTEM.equals(temp.getResourcetype())))
				{
					CloneResources cloe = new CloneResources();
					cloe.setId(temp.getId());
					if(null == temp.getParent()||(temp.getParent()!=null&&rootId.equals(temp.getParent().getId())))
					{
						cloe.setParentId(null);
					}
					else
					{
						cloe.setParentId(temp.getParent().getId()+"");
					}
					cloe.setName(temp.getName());
					cloe.setIcon(temp.getIcon());
					cloe.setLink(temp.getLink());
					resource.add(cloe);
				}
			}
			
			// 业务数据解码器，从业务数据中分解出id和parentid
			UserDataUncoder orgUncoder = new UserDataUncoder() {
				public Object getID(Object pUserData) throws UncodeException {
					CloneResources org = (CloneResources) pUserData;
					return org.getId();
				}

				public Object getParentID(Object pUserData) throws UncodeException {
					CloneResources org = (CloneResources) pUserData;
					return null == org.getParentId()?null:Integer.valueOf(org.getParentId());
				}
			};

			// Tree模型构造器，用于生成树模型
			AbstractWebTreeModelCreator treeModelCreator = new AbstractWebTreeModelCreator() {
				// 该方法负责将业务数据映射到树型节点
				protected Node createNode(Object pUserData, UserDataUncoder pUncoder) {
					CloneResources org = (CloneResources) pUserData;
					WebTreeNode result = new WebTreeNode(org.getName(), "node"+org.getId());
					result.setIcon(org.getIcon());
					result.setAction(org.getLink());
					return result;
				}
			};
			
			String temp = Utils.getResourcesWebTree(orgUncoder, treeModelCreator, resource, request);
			request.setAttribute("treescript", temp);
			
			*/
			
			
			if("taskList".equals(targetName))
			{
				return "taskList";
			}
			else
			{
				return "success";
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "error";
		}		
	}
	private List<MenuJsonItem> treeGen(Resources item,List<Resources> list)
	{
		List<MenuJsonItem> menuList = new ArrayList<MenuJsonItem>();
		List<MenuJsonItem> firstSubMenus = new ArrayList<MenuJsonItem>();
		MenuJsonItem jsonItem = new MenuJsonItem();
		jsonItem.setMenuid(item.getId()+"");
		jsonItem.setMenuname(item.getName());
		jsonItem.setIcon(item.getIcon());
		jsonItem.setOrder(item.getOrderid());
		//判断该子菜单，如果有叶子，全部归于该子菜单，如果有目录则归为同级菜单
		for(int i=0;i<list.size();i++)
		{	
			Resources tmp = list.get(i);
			if(tmp.getParent()!=null&&tmp.getParent().getId()==item.getId())
			{
				if(tmp.getLink()!=null&&tmp.getLink().length()>2)
				{
					MenuJsonItem tmpItem = new MenuJsonItem();
					tmpItem.setMenuid(tmp.getId()+"");
					tmpItem.setMenuname(tmp.getName());
					tmpItem.setIcon(tmp.getIcon());
					tmpItem.setOrder(tmp.getOrderid());
					tmpItem.setUrl(tmp.getLink());
					firstSubMenus.add(tmpItem);
				}
				else
				{
					menuList.add(subTreeGen(list.get(i),list));
				}
				
			}
		}
		//排序
		if(firstSubMenus.size()>0)
		{
			Collections.sort(firstSubMenus);
			jsonItem.setMenus(firstSubMenus);
		}
		menuList.add(0,jsonItem);
		Collections.sort(menuList);
		return menuList;
	}
	private MenuJsonItem subTreeGen(Resources item,List<Resources> list)
	{
		MenuJsonItem jsonItem = new MenuJsonItem();
		jsonItem.setMenuid(item.getId()+"");
		jsonItem.setMenuname(item.getName());
		jsonItem.setIcon(item.getIcon());
		jsonItem.setOrder(item.getOrderid());
		if(item.getLink()!=null&&item.getLink().length()>2)
			jsonItem.setUrl(item.getLink());
		List<MenuJsonItem> menus = new ArrayList<MenuJsonItem>();
		for(int i=0;i<list.size();i++)
		{
				
			if(list.get(i).getParent()!=null&&list.get(i).getParent().getId()==item.getId())
			{
				menus.add(subTreeGen(list.get(i),list));
			}
		}
		if(menus.size()>0)
		{
			Collections.sort(menus);
			jsonItem.setMenus(menus);
		}
			
		return jsonItem;
	}	
	public String logout(){
			SecurityUtils.getSubject().logout();
			return "error";
	}
	

}
